const { server } = require('../config')
const jwt = require('jsonwebtoken')
const fs = require('fs')
const path = require('path')
const { NotFound } = require('../core/http-exception')

function createString(data, num) {
  let result = ''
  for (let i = 0; i < num; i++) {
    result += data[random(data.length)]
  }
  return result
}

function random(num) {
  return Math.floor(num * Math.random())
}

function createAuthCode() {
  return createString('0123456789', 6)
}

function createID(r){
  return createString(`0123456789qwertyuiopasdfghjklzxcvbnm${r.replace(/\W/g, '')}`.toLocaleUpperCase(), 32);
}

class HttpDataResolve {
  success(msg = 'success', code = 200) {
    return {
      msg,
      code
    }
  }

  json(data, msg = 'success', code = 200) {
    return {
      data,
      msg,
      code
    }
  }
}

function generateToken(id, uid, scope){
  const token = jwt.sign({
    id, uid, scope
  }, server.auth.secretKey, {
    expiresIn: server.auth.expires
  })
  return token;
}

function isFile(path){
  return new Promise((resolve, reject) => {
    fs.exists(path, flag => {
      resolve(flag)
    })
  })
}

async function isImgExists(p){
  const img = await isFile(path.join(__dirname, '../static', p))
  const t = p.split('.')
  const ts = ['jpg', 'jpeg', 'png'];
  
  if (!img || !ts.includes(t[t.length - 1])) {
    throw new NotFound(`路径为"${p}"的图片不存在`)
  }
}

async function isModelOne(type, id){
  const { User, Article, Comment } = require('../models')
  let model = null
  switch (type) {
    case 'user':
      model = User
      break
    case 'article':
      model = Article
      break
    case 'comment':
      model = Comment
      break
  }

  if (!model) {
    throw new NotFound('没有找到相关数据')
  }
  const result = await model.findOne({ where: { id } });
  if(!result){
    throw new NotFound('没有找到相关数据')
  }
  return result;
}

async function getLike(type, id, user_id = 0){
  const { Like } = require('../models')

  const count = await Like.count({
    where: {
      type, target_id: id
    }
  });

  const user = await Like.findOne({
    where: {
      type, target_id: id, user_id
    }
  })

  return {
    count, user_like: !!user
  }
}

module.exports = {
  createString,
  random,
  createAuthCode,
  HttpDataResolve,
  generateToken,
  isFile,
  isImgExists,
  isModelOne,
  getLike,
  createID
}
